package com.example.kotlineventtracker.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.kotlineventtracker.model.EventInfo
import com.example.kotlineventtracker.model.EventInfoRequestBody
import com.example.kotlineventtracker.util.EventRepository
import kotlinx.coroutines.launch

class EventInfoViewModel(application: Application) : AndroidViewModel(application) {

    // 获取 EventRepository 的单例实例
    private val repository: EventRepository = EventRepository.getInstance(application.applicationContext)

    private val _events = MutableLiveData<List<EventInfo>>()
    val events: LiveData<List<EventInfo>> get() = _events

    fun loadEventInfo(eventId: String, eventType: String) {
        // 设置请求body
        val request = EventInfoRequestBody(
            eventId = eventId,
            eventType = eventType
        )

        viewModelScope.launch {
            try {
                repository.fetchEventInfo(
                    request,
                    onSuccess = { infoResponse ->
                        if (infoResponse != null && infoResponse.data != null) {
                            _events.value = infoResponse.data
                        } else {
                            _events.value = emptyList()
                        }
                    },
                    onFailure = { throwable ->
                        throwable.printStackTrace()
                        _events.value = emptyList()
                    }
                )
            } catch (e: Exception) {
                e.printStackTrace()
                _events.value = emptyList()
            }
        }
    }
}
